package com.papercutting.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.papercutting.platform.entity.Banner;
import com.papercutting.platform.repository.BannerRepository;
import com.papercutting.platform.service.BannerService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 轮播图服务实现类
 */
@Service
public class BannerServiceImpl implements BannerService {
    
    private final BannerRepository bannerRepository;
    
    public BannerServiceImpl(BannerRepository bannerRepository) {
        this.bannerRepository = bannerRepository;
    }
    
    @Override
    public Banner save(Banner banner) {
        if (banner.getId() == null) {
            bannerRepository.insert(banner);
        } else {
            bannerRepository.updateById(banner);
        }
        return banner;
    }

    @Override
    public Banner findById(Long id) {
        Banner banner = bannerRepository.selectById(id);
        return banner;
    }

    @Override
    public List<Banner> findAll() {
        return bannerRepository.selectList(null);
    }

    @Override
    public Page<Banner> findAll(Pageable pageable) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Banner> page =
            new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(
                pageable.getPageNumber() + 1, pageable.getPageSize());
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Banner> result =
            bannerRepository.selectPage(page, null);
        return new PageImpl<>(result.getRecords(), pageable, result.getTotal());
    }

    @Override
    public void deleteById(Long id) {
        bannerRepository.deleteById(id);
    }

    @Override
    public List<Banner> findByStatus(Integer status) {
        QueryWrapper<Banner> wrapper = new QueryWrapper<>();
        wrapper.eq("status", status);
        return bannerRepository.selectList(wrapper);
    }

    @Override
    public List<Banner> findByStatusAndTimeRange(Integer status, LocalDateTime now) {
        QueryWrapper<Banner> wrapper = new QueryWrapper<>();
        wrapper.eq("status", status)
               .and(w -> w.isNull("start_time").or().le("start_time", now))
               .and(w -> w.isNull("end_time").or().ge("end_time", now))
               .orderByAsc("sort_order");
        return bannerRepository.selectList(wrapper);
    }

    @Override
    public List<Banner> findActiveByOrderBySortOrderAsc() {
        QueryWrapper<Banner> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1)
               .orderByAsc("sort_order");
        return bannerRepository.selectList(wrapper);
    }
}